package com.qf.service.impl;

import com.qf.dao.OrderDao;
import com.qf.dao.OrderDetailDao;
import com.qf.dao.impl.OrderDaoImpl;
import com.qf.dao.impl.OrderDetailDaoImpl;
import com.qf.domain.Cart;
import com.qf.domain.Order;
import com.qf.domain.OrderDetail;
import com.qf.service.CartService;
import com.qf.service.OrderService;
import com.qf.util.DataSourceUtils;
import com.qf.util.RandomUtils;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 * @version v1.0
 * @date 2022/4/20
 */
public class OrderServiceImpl implements OrderService {
    CartService cartService = new CartServiceImpl();
    OrderDao orderDao = new OrderDaoImpl();
    OrderDetailDao orderDetailDao = new OrderDetailDaoImpl();
    @Override
    public Order addOrder(int uid, String aid) {
        try {
            DataSourceUtils.begin();
            List<Cart> carts = cartService.findCardByUid(uid);
            double sum =0;
            for (Cart cart : carts) {
                sum+=cart.getMoney();
            }

            Order order = new Order();
            order.setId(RandomUtils.createActive());
            order.setUid(uid);
            order.setMoney(sum);
            order.setStatus("未支付");
            order.setTime(new Date());
            order.setAid(Integer.parseInt(aid));
            orderDao.insert(order);


            for (Cart cart : carts) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOid(order.getId());
                orderDetail.setPid(cart.getPid());
                orderDetail.setNum(cart.getNum());
                orderDetail.setMoney(cart.getMoney());

                orderDetailDao.insert(orderDetail);
            }

            cartService.clearCart(uid);


            DataSourceUtils.commit();
            return order;
        } catch (SQLException e) {
            try {
                DataSourceUtils.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            System.out.println("添加订单失败");
        }finally {
            try {
                DataSourceUtils.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
